<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>以上js代码可以通过HTML代码来调用</title>
    <script>
        function validateForm() {
            var x = document.forms["myForm"]["fname"].value;
            if (x == null || x == "") {
                alert("需要输入名字。");
                return false;
            }
        }
    </script>
</head>

<body>
    <form name="myForm" action="demo_form.php" onsubmit="return validateForm()" method="post">
        名字: <input type="text" name="fname">
        <input type="submit" value="提交">
    </form>
</body>

</html>